package com.tanhua.admin.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.constants.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.dto.LoginDto;
import com.tanhua.model.vo.AdminVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.SecurityUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    public LineCaptcha getVerification(String uuid) {
        //生成验证码对象
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 150);
        //将验证码存入redis(设置失效时间：5分钟)
        String code = lineCaptcha.getCode();
        System.err.println("验证码：" + code);
        redisTemplate.opsForValue().set(Constants.CAP_CODE + uuid, code, 5L, TimeUnit.MINUTES);
        return lineCaptcha;
    }

    /**
     * 系统框架-用户登录
     * @param loginDto
     * @return
     */
    public Map<String, String> login(LoginDto loginDto) {
        //判断验证码是否为空
        String verificationCode = loginDto.getVerificationCode();
        if (StringUtils.isEmpty(verificationCode)) {
            throw new BusinessException("请输入验证码！");
        }
        //判断用户名密码是否为空
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new BusinessException("用户名或密码错误！");
        }
        //判断验证码是否正确
        String uuid = loginDto.getUuid();
        String key = Constants.CAP_CODE + uuid;
        String codeInRedis = redisTemplate.opsForValue().get(key);
        if (!verificationCode.equals(codeInRedis)) {
            throw new BusinessException("验证码有误！");
        }
        //判断账号密码是否正确
        password = SecureUtil.md5(password);
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername, username).eq(Admin::getPassword, password);
        Admin admin = adminMapper.selectOne(wrapper);
        if (ObjectUtil.isEmpty(admin)) {
            throw new BusinessException("用户名或密码错误！");
        }
        //通过JWT生成token
        Map<String, String> map = new HashMap<>();
        map.put("id", admin.getId().toString());
        map.put("username", username);
        String token = JwtUtils.getToken(map);
        //构造返回值
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);

        log.info("用户{}登录成功！", username);
        return tokenMap;
    }

    /**
     * 系统框架-用户基本信息
     * @return
     */
    public AdminVO getProfile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        return AdminVO.init(admin);
    }

    /**
     * 系统框架-用户登出
     * @return
     */
    public void logout() {
        Long userId = AdminHolder.getUserId();
        log.info("用户已退出登录！");
    }
}
